package com.idanchuang.component.logback.filter;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.idanchuang.component.core.util.SpringUtil;
import com.idanchuang.component.logback.config.LogbackSentryConfig;

import java.util.List;

public class SentryLogFilter extends Filter<ILoggingEvent> {

    private LogbackSentryConfig logbackSentryConfig = null;

    @Override
    public FilterReply decide(ILoggingEvent iLoggingEvent) {
        initConfig();
        if (logbackSentryConfig == null || !logbackSentryConfig.isEnabled()) {
            return FilterReply.DENY;
        }
        List<String> whiteList = logbackSentryConfig.getWhiteList();
        if (whiteList != null && !whiteList.isEmpty()) {
            StringBuilder messageBuilder = new StringBuilder(iLoggingEvent.getFormattedMessage());
            IThrowableProxy throwableProxy = iLoggingEvent.getThrowableProxy();
            while (throwableProxy != null) {
                messageBuilder.append("\n").append(throwableProxy.getMessage());
                throwableProxy = throwableProxy.getCause();
            }
            String message = messageBuilder.toString();
            if (whiteList.stream().anyMatch(message::contains)) {
                return FilterReply.DENY;
            }
        }
        return FilterReply.NEUTRAL;
    }

    private void initConfig() {
        if (logbackSentryConfig == null) {
            synchronized (SentryLogFilter.class) {
                logbackSentryConfig = SpringUtil.getBean(LogbackSentryConfig.class);
            }
        }
    }

}
